var express = require('express');
var router = express.Router();
const md5 = require('md5')

const UserModel = require('../../models/UserModel')

// 注册
router.get('/reg', (req, res) => {
  res.render('auth/reg')
})

// 注册
router.post('/reg', (req, res) => {
  // console.log(req.body)
  // 插入数据库
  UserModel.create({
    ...req.body,
    password: md5(req.body.password)
  }).then(data => {
    // 成功提示
    res.render('success', {msg: '注册成功哦~~~', url: '/login'})
  }).catch(err => {
    res.status(500).send('注册失败~')
    console.log(err)
    return
  })
})

// 登录
router.get('/login', (req, res) =>{
  res.render('auth/login')
})

// 登录
router.post('/login', (req, res) =>{
  let { username, password } = req.body
  UserModel.findOne({username, password: md5(password)}).then(data => {
    if(!data) {
      return res.send('账号或密码错误~')
    }
    // 写入session
    req.session.username = data.username
    req.session._id = data._id
    res.render('success', {msg: '登录成功', url: '/account'})
  }).catch(err => {
    res.status(500).send('登录失败~')
    console.log(err)
    return
  })
})

// 退出登录
router.post('/logout', (req, res) => {
  req.session.destroy(() => {
    res.render('success', {msg: '退出成功', url: '/login'})
  })
})

module.exports = router;
